package com.syx.friend.Manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.syx.common.redis.Service.RedisService;
import com.syx.commoncore.Constant.CacheConstant;
import com.syx.commoncore.Constant.Constant;
import com.syx.commoncore.enums.ExamListType;
import com.syx.commoncore.enums.Resultcode;
import com.syx.friend.Mapper.ExamQuestionMapper;
import com.syx.friend.Mapper.ExamMapper;
import com.syx.friend.Mapper.UserExamMapper;
import com.syx.friend.Model.exam.DTO.ExamQueryDTO;
import com.syx.friend.Model.exam.DTO.ExamRankDTO;
import com.syx.friend.Model.exam.Exam;
import com.syx.friend.Model.exam.ExamQuestion;
import com.syx.friend.Model.exam.VO.ExamRankVO;
import com.syx.friend.Model.exam.VO.ExamVO;
import com.syx.friend.Model.user.UserExam;
import com.syx.friend.Model.user.UserScore;
import com.syx.security.Exception.ServiceException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class ExamCacheManager {

    @Resource
    private RedisService redisService;

    @Resource
    ExamMapper examMapper;

    @Resource
    UserExamMapper userExamMapper;

    @Resource
    ExamQuestionMapper examQuestionMapper;

    public Long getListSize(Integer examListType, Long userId) {
        String examListKey = getExamListKey(examListType, userId);
        return redisService.getListSize(examListKey);
    }
    public void refreshExamQuestionCache(Long examId) {
        //刷新竞赛中包含所有的题目
        List<ExamQuestion> examQuestions = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if (CollectionUtil.isEmpty(examQuestions)){
            //如果数据库中也没查到直接返回不做了
            return;
        }
        //数据库中有数据，获取到竞赛下的questionId
        List<Long> examQuestionIdList = examQuestions.stream().map(ExamQuestion::getQuestionId).toList();
        redisService.rightPushAll(getExamQuestionListKey(examId),examQuestionIdList);
        //设置有效时间，查的时候再刷新，因为竞赛开始的时候不能进行修改，查的人就不错，即使修改了等待后面刷新了再重新等时间再刷 一遍
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getExamQuestionListKey(examId), seconds, TimeUnit.SECONDS);


    }


    public void refreshCache(Integer examListType, Long userId) {
        List<Exam> examList = new ArrayList<>();

        if (Objects.equals(examListType, ExamListType.EXAM_HISTORY_LIST.getValue())) {
            // 查询历史竞赛：结束时间小于当前时间
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime,Exam::getStatus)
                    .lt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constant.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (Objects.equals(examListType,  ExamListType.EXAM_UN_FINISH_LIST.getValue())) {
            // 查询进行中或未开始的竞赛：开始时间大于等于当前时间
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime,Exam::getStatus)
                    // 修改为结束时间大于当前时间
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constant.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        }else if (Objects.equals(examListType,  ExamListType.USER_EXAM_LIST.getValue())){
            //查询用户竞赛列表
            List<ExamVO> examVOList=userExamMapper.selectUserExamList(userId);
            examList=BeanUtil.copyToList(examVOList,Exam.class);


        }


        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }

        // 写入 Redis 缓存
        redisService.multiSet(examMap);  // 缓存每个竞赛的详细信息
        String examListKey = getExamListKey(examListType, userId);
        redisService.deleteObject(examListKey);  // 删除旧缓存
        redisService.rightPushAll(examListKey, examIdList);  // 推送新的竞赛 ID 列表
    }

    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        String examListKey = getExamListKey(examQueryDTO.getType(), userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            examVOList = getExamListByDB(examQueryDTO, userId); //从数据库中获取数据
            refreshCache(examQueryDTO.getType(), userId);
        }
        return examVOList;
    }
    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO, Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if (ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())){
            return userExamMapper.selectUserExamList(userId);
        }
        else {
            return examMapper.selectExamList(examQueryDTO);
        }
    }
    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    //返回排名数量
    public Long getRankListSize(Long examId) {
        return redisService.getListSize(getExamRankListKey(examId));
    }
    public List<ExamRankVO> getExamRankList(ExamRankDTO examRankDTO) {
        int start = (examRankDTO.getPageNum() - 1) * examRankDTO.getPageSize();
        int end = start + examRankDTO.getPageSize() - 1; //下标需要 -1
        return redisService.getCacheListByRange(getExamRankListKey(examRankDTO.getExamId()), start, end, ExamRankVO.class);
    }



    //获取竞赛下的排名的key
    private String getExamRankListKey(Long examId) {
        return CacheConstant.EXAM_RANK_LIST + examId;
    }





    //返回未完赛列表
    private String getExamListKey(Integer examListType, Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstant.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstant.EXAM_HISTORY_LIST;
        } else {
            return CacheConstant.USER_EXAM_LIST + userId;
        }
    }

    //获取得到个人竞赛列表的key
    public String getUserExamListKey(Long userId){
        return CacheConstant.USER_EXAM_LIST+userId;

    }
    public void addUserExamCache(Long userId,Long examId){
        String userExamListKey = getUserExamListKey(userId);
        redisService.leftPushForList(userExamListKey,examId);



    }



    //竞赛详细信息+examId为另外一个的key
    private String getDetailKey(Long examId) {
        return CacheConstant.EXAM_DETAIL + examId;
    }

    //获取查找竞赛下questionId的Key e:q:l:+examId
    private String getExamQuestionListKey(Long examId) {
        return CacheConstant.EXAM_QUESTION_LIST + examId;
    }

    public List<Long> getAllUserExamList(Long userId) {
        //获取数据
        String examListKey = CacheConstant.USER_EXAM_LIST+userId;
        //获取所有的userId对应的examId。
        List<Long> userExaIdByRange = redisService.getCacheListByRange(examListKey, 0, -1, Long.class);
        //如果不为空
        if (CollectionUtil.isNotEmpty(userExaIdByRange)){
            return userExaIdByRange;
        }
        //为空
        List<UserExam> userExams = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>().eq(UserExam::getUserId, userId));
        if (CollectionUtil.isEmpty(userExams)){
            //就算从数据库中查也没有了，那就是真的没有
            return null;
        }
        //刷新缓存，为了保证健壮性，但是其实没有必要因为从数据库中查询过一次了
        refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
        //将所有的userExams中的examId查出来放到一个新的list中
        return userExams.stream().map(UserExam::getExamId).collect(Collectors.toList());


    }




    //获取竞赛下题目的数量
    public Long getExamQuestionListSize(Long examId){
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);


    }

    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId),0,Long.class);


    }

    public Long preQuestion(Long examId,Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        //有可能是第一题
        if (index==0){
            throw new ServiceException(Resultcode.FAILED_FIRST_QUESTION);
        }
        //获取上一题的id
        return redisService.indexForList(getExamQuestionListKey(examId), index - 1, Long.class);



    }

    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId) , questionId);
        //有可能是第一题
        Long examQuestionListSize = getExamQuestionListSize(examId)-1;
        if (Objects.equals(index, examQuestionListSize)){
            throw new ServiceException(Resultcode.FAILED_LAST_QUESTION);
        }
        //获取上一题的id
        return redisService.indexForList(getExamQuestionListKey(examId), index +1, Long.class);
    }

    public void refreshExamRankCache(Long examId) {
        //从缓存中刷数据

        List<ExamRankVO> examRankVOS = userExamMapper.selectExamRankList(examId);


        List<UserScore> individualUserScores = BeanUtil.copyToList(examRankVOS, UserScore.class);

        for (UserScore individualUserScore : individualUserScores) {
            individualUserScore.setExamId(examId);
        }

        if (CollectionUtil.isEmpty(individualUserScores)){
            return;
        }
        String examRankListKey = getExamRankListKey(examId);
        redisService.setCacheObject(examRankListKey,individualUserScores);
    }


    //获取查找竞赛下questionId的Key e:q:l:+examId

}